function sendMessage() {
  const userInput = document.getElementById('user-input')
  const chatMessages = document.getElementById('chat-messages')

  const message = userInput.value.trim()
  if (!message) return

  // 显示用户消息
  addMessage('user-message', message)

  // 清空输入框
  userInput.value = ''

  // 创建一个新的消息 div，用于实时更新 AI 回复
  const aiMessageDiv = addMessage('ai-message', '...')

  // 使用 EventSource 模拟流式响应
  fetch('http://localhost:3000/proxy', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      model: 'generalv3.5',
      messages: [{ role: 'user', content: message }],
      stream: true,
    }),
  })
    .then((response) => {
      const reader = response.body.getReader()
      const decoder = new TextDecoder('utf-8')
      let aiResponse = ''

      function readStream() {
        reader.read().then(({ done, value }) => {
          if (done) {
            // 如果完成，更新最终的 AI 消息
            aiMessageDiv.textContent = aiResponse
            return
          }

          // 解码数据块
          const chunk = decoder.decode(value, { stream: true })
          const lines = chunk.split('\n').filter((line) => line.trim() !== '')

          // 处理每行数据
          for (const line of lines) {
            if (line === 'data: [DONE]') {
              // 流结束标志
              return
            }

            try {
              const json = JSON.parse(line.replace(/^data: /, ''))
              const content = json.choices[0]?.delta?.content || ''
              aiResponse += content

              // 实时更新 AI 消息
              aiMessageDiv.textContent = aiResponse
            } catch (error) {
              console.error('Error parsing line:', line, error)
            }
          }

          // 继续读取下一块数据
          readStream()
        })
      }

      // 开始读取流数据
      readStream()
    })
    .catch((error) => {
      console.error('Error:', error)
      aiMessageDiv.textContent = 'Failed to fetch response from the server.'
    })
}

// 添加消息到聊天界面
function addMessage(className, message) {
  const chatMessages = document.getElementById('chat-messages')
  const messageDiv = document.createElement('div')
  messageDiv.className = `chat-message ${className}`
  messageDiv.textContent = message
  chatMessages.appendChild(messageDiv)
  chatMessages.scrollTop = chatMessages.scrollHeight
  return messageDiv
}
